////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.adapter.OilQuoteItemAdapter;
import cc.telecomdigital.tdstock.adapter.OilQuoteViewHolder;
import cc.telecomdigital.tdstock.model.OilInfo;
import cc.telecomdigital.tdstock.view.LinearLayoutForListView;

/**
 * 
 * @author haibo
 * 
 *         for list item named "Oil quote"
 * 
 */
public class OilQuoteActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String			TAG					= OilQuoteActivity.class
																.getSimpleName();
	private static final int				HISTORY_LIST_SIZE_LIMIT	= 10;
	private final static Calendar			calendar				= Calendar.getInstance();

	private static final long			START_ID				= 90000l;

	private LinearLayoutForListView		_listView;
	private Button						_toolBtnReturn;
	private TextView					_oil_nominal_value;
	private TextView					_oil_net_value;
	private TextView					_oil_netpercentage_value;

	private TextView					_oil_prev_value;
	private TextView					_oil_prev_net_value;
	private TextView					_oil_high_value;
	private TextView					_oil_low_value;

	private Button						_addToMonitor;

	private static OilQuoteItemAdapter		_quotedapter;
	private static List<OilQuoteViewHolder>	_quoteList;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.oil_quote);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG,
						"close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(),
						MoreActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(MoreActivity.class, intent);
			}
		});

		_oil_nominal_value = (TextView) findViewById(R.id.more_oil_nominal_value);
		_oil_net_value = (TextView) findViewById(R.id.more_oil_net_value);
		_oil_netpercentage_value = (TextView) findViewById(R.id.more_oil_netpercentage_value);

		_oil_prev_value = (TextView) findViewById(R.id.more_oil_prev_value);
		_oil_prev_net_value = (TextView) findViewById(R.id.more_oil_prev_net_value);
		_oil_high_value = (TextView) findViewById(R.id.more_oil_high_value);
		_oil_low_value = (TextView) findViewById(R.id.more_oil_low_value);

		_addToMonitor = (Button) findViewById(R.id.add_oil_to_monitor);
		{
			AddOilClickHandler handler = new AddOilClickHandler(this);
			handler.setAdapter(OilInfo.ADAPTER);
			handler.setItem(OilInfo.SUBSCRIBE_ITEMS_CODE[0]);
			handler.setIconName(OilInfo.SUBSCRIBE_ITEMS_NAME_4_ICON[0]);
			handler.setFields(OilInfo.SUBSCRIBE_ITEMS_NAME_4_MONITOR[0],
					OilInfo.LAST, OilInfo.NET, "");
			_addToMonitor.setOnClickListener(handler);
		}

		_listView = (LinearLayoutForListView) findViewById(R.id.more_oil_close_price_list);

		_quoteList = new ArrayList<OilQuoteViewHolder>();
		_quotedapter = new OilQuoteItemAdapter(LayoutInflater.from(this),
				_quoteList);
		_listView.setAdapter(_quotedapter);
	}

	protected Context getMyOwnContext()
	{
		return getParent();
	}

	private void updateAdapter()
	{
		_listView.updateView();
	}

	// @Override
	// protected void onResume()
	// {
	// super.onResume();
	// }

	private class AddOilClickHandler extends DefaultClickHandler
	{
		private String	_item;
		private String	_adapter;
		private String	_fieldName;
		private String	_fieldValue;
		private String	_fieldNet;
		private String	_fieldNetPercentage;
		private String	_iconName;

		public AddOilClickHandler(Context context)
		{
			super(context);
		}

		public void setItem(String item)
		{
			_item = item;
		}

		public void setIconName(String icnName)
		{
			_iconName = icnName;
		}

		public void setAdapter(String adapter)
		{
			_adapter = adapter;
		}

		public void setFields(String name, String value, String net,
				String netpercentage)
		{
			_fieldName = name;
			_fieldValue = value;
			_fieldNet = net;
			_fieldNetPercentage = netpercentage;
		}

		@Override
		protected void onDefaultAction()
		{
			if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.DELARY)
			{

				DBHelper dbHelper = new DBHelper(OilQuoteActivity.this);
				try
				{
					int customerId = 1;
					if (dbHelper.isSubscribeItemExist(customerId, _item,
							_adapter))
					{
						new CustomizeDialog(getMyOwnContext(), "",
								getResources().getString(
										R.string.monitor_exist_index))
								.show();
					}
					else if (dbHelper.isFullWithItemInMonitor(customerId))
					{
						new CustomizeDialog(
								getMyOwnContext(),
								"",
								getResources()
										.getString(
												R.string.monitor_is_full_with_items))
								.show();
					}
					else
					{
						long result = dbHelper.insertSubscribeItem(
								customerId, _item, _adapter,
								_fieldName, _fieldValue, _fieldNet,
								_fieldNetPercentage);

						if (result > 0)
						{
							startAnimat(_iconName == null ? _item
									: _iconName); /*
														 * modify
														 * by
														 * zor
														 * (
														 * ouyangzhihui
														 * )
														 * -
														 * start
														 */
						}

						TDStockLog.d(TAG, "insert result:" + result);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
					TDStockLog.d(
							TAG,
							"insert result:" + e.getMessage() == null ? "unknown exception!"
									: e.getMessage());
				}
				finally
				{
					dbHelper.cleanup();
				}
			}
			else
			{

				/*
				 * if(_messageHandler == null) { _messageHandler = new
				 * Handler(); }
				 * 
				 * if(MonitorUtil.getInstance().addBookMarkItem(_item,
				 * CommonDefn
				 * .BookMarkType.oil.getBookMarkType(),OilQuoteActivity.this)){
				 * 
				 * _messageHandler.post(new SaveMonitor(_item.length() >= 5 ?
				 * _item.substring(0, 5) :
				 * _item,MonitorUtil.items,OilQuoteActivity.this)); }
				 */

				new SaveBookMarkAsyncTask(_item,
						CommonDefn.BookMarkType.oil.getBookMarkType(),
						OilQuoteActivity.this, MonitorUtil.getInstance(),
						_item.length() >= 5 ? _item.substring(0, 5)
								: _item).execute();

			}
		}
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}

	private void updateUI(List<String[]> result)
	{
		if (result == null || result.isEmpty() || result.get(0).length < 3)
		{
			return;
		}
		for (String[] array : result)
		{
			_oil_nominal_value.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					array[0] == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: array[0]));
			_oil_nominal_value.postInvalidate();
			String netStr = StringUtils
					.formatToFiveCharsRule(array[1] == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: array[1]);
			_oil_net_value.setText(netStr);
			if (array[1] != null && array[1].indexOf("-") >= 0)
			{
				_oil_net_value.setTextColor(Color.RED);
				_oil_netpercentage_value.setTextColor(Color.RED);
			}
			else
			{
				_oil_net_value.setTextColor(Color.GREEN);
				_oil_netpercentage_value.setTextColor(Color.GREEN);
			}
			_oil_net_value.postInvalidate();

			try
			{
				double net = Double.parseDouble(array[1]);
				double now = Double.parseDouble(array[0]);
				double netPercentage = ((now) / (now - net) - 1) * 100.00d;
				_oil_netpercentage_value.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.NETPERCENTAGE,
						String.valueOf(netPercentage)));
				_oil_netpercentage_value.postInvalidate();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

			_oil_prev_value.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					array[2] == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: array[2]));
			_oil_prev_value.postInvalidate();

			_oil_high_value.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					array[3] == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: array[3]));
			_oil_high_value.postInvalidate();

			_oil_low_value.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					array[4] == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: array[4]));
			_oil_low_value.postInvalidate();

			break; // there's only one row;
		}
	}

	private void updateDataByPrevClose(List<String[]> list)
	{
		_quoteList.clear();

		int index = 0;
		long id = START_ID + _quoteList.size();
		while (index <= HISTORY_LIST_SIZE_LIMIT)
		{
			String[] array = list.get(index);
			String date = array[0];
			String last = array[1];
			String net = array[2];

			if (1 + calendar.get(Calendar.MONTH) == Integer.parseInt(
					date.substring(5, 7), 10)
					&& calendar.get(Calendar.DATE) == Integer.parseInt(
							date.substring(8, 10), 10))
			{
				index += 1;
				continue;
			}
			OilQuoteViewHolder holder = new OilQuoteViewHolder();
			holder.id = id + index;
			holder.date = new TextView(OilQuoteActivity.this);
			holder.date.setText(String.format("%s月%s日",
					date.substring(5, 7), date.substring(8, 10)));
			TDStockLog.d(
					TAG,
					" DATE- "
							+ String.format("%s月%s日",
									date.substring(5, 7),
									date.substring(8, 10)));
			holder.month = Integer.parseInt(date.substring(5, 7), 10);
			holder.day = Integer.parseInt(date.substring(8, 10), 10);
			holder.value = new TextView(OilQuoteActivity.this);
			holder.value
					.setText(last == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: last);
			holder.net = new TextView(OilQuoteActivity.this);
			holder.net.setText(net == null ? CommonDefn.DEFAULT_FIELD_VALUE
					: net);

			{
				if (!_quoteList.isEmpty())
				{
					OilQuoteViewHolder tmpHolder = _quoteList
							.get(_quoteList.size() - 1);
					if (tmpHolder.date.getText().toString()
							.equals(holder.date.getText().toString()))
					{
						_quoteList.remove(_quoteList.size() - 1);
					}
				}
			}
			_quoteList.add(holder);
			index += 1;
		}

		final Runnable runnable = new Runnable()
		{
			public void run()
			{
				updateAdapter();
				for (OilQuoteViewHolder holder : _quoteList)
				{
					if (1 + calendar.get(Calendar.MONTH) == holder.month
							&& calendar.get(Calendar.DATE) - 1 >= holder.day)
					{
						try
						{
							String net = holder.net.getText().toString();

							String netStr = StringUtils
									.formatToFiveCharsRule(net);
							_oil_prev_net_value.setText(netStr);
							_oil_prev_net_value.setTextColor(net
									.indexOf("-") >= 0 ? Color.RED
									: Color.GREEN);
							_oil_prev_net_value.postInvalidate();
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
						break;
					}
				}
			}
		};
		_messageHandler.post(runnable);
	}

	private boolean	iSendFrist	= true;

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		H_CODE statusCode;
		if (iSendFrist)
			statusCode = HttpAppInfo.SendOilQuoteRequest(actContext, this,
					"OilHeader");
		else
			statusCode = HttpAppInfo.SendOilQuotePrevCloseRequest(
					actContext, this, "OilPrevClose");
		return statusCode;
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(
			final H_UserClient_HttpRequest_Result iResult)
	{
		if (!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}

		if ("OilHeader".equals(iResult.seqID))
		{
			Runnable runnable = new Runnable()
			{
				@Override
				public void run()
				{
					updateUI(iResult.contentStores);
				}
			};
			_messageHandler.post(runnable);

			iSendFrist = false;
			SendHttpRequest();
		}
		else if ("OilPrevClose".equals(iResult.seqID))
		{
			Runnable runnable = new Runnable()
			{
				@Override
				public void run()
				{
					updateDataByPrevClose(iResult.contentStores);
				}
			};
			_messageHandler.post(runnable);
		}
	}
}
